package com.yk.rabbitmq.routing;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.MessageProperties;

import java.io.IOException;


public class Producer {

    public static void main(String[] args) {
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("localhost");
        connectionFactory.setPort(5672);
        connectionFactory.setUsername("admin");
        connectionFactory.setPassword("12345");
        connectionFactory.setVirtualHost("/faith");

        Connection connection = null;
        Channel channel = null;
        try {
            connection = connectionFactory.newConnection("生产者");
            channel = connection.createChannel();
            String queueName = "queue1";
            String exchangeName = "fanout-exchange";
            String routeKey = "";
            String type = "fanout";
            /*
             * 队列声明
             * @params1 队列名称
             * @params2 是否要持久化
             * @params3 排他性，是否独占独立
             * @params4 是否自动删除，随着随后一个消费者消费完毕以后是否把队列自动删除
             * @params5 携带的附加参数
             */
            String message = "第一次发送消息";
            //声明交换机
            channel.exchangeDeclare(exchangeName, type,true);

            //声明队列并绑定交换机
            channel.queueDeclare("队列1", true, false, false, null);
            channel.queueBind("队列1", exchangeName, "");
            channel.queueDeclare("队列2", true, false, false, null);
            channel.queueBind("队列2", exchangeName, "");
            channel.queueDeclare("队列3", true, false, false, null);
            channel.queueBind("队列3", exchangeName, "");
            /*
             * 发送消息到交换机
             * @params1 交换机名
             * @params2 队列、路由key
             * @params3 消息状态控制
             * @params4 消息主题
             */
            channel.basicPublish(exchangeName, routeKey, null, message.getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //关闭连接
            if (channel != null && channel.isOpen()) {
                try {
                    connection.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

}
